package com.freecat.xmqgct.mvp.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.freecat.xmqgct.R;
import com.freecat.xmqgct.utils.Tools;
import com.freecat.xmqgct.utils.TsUtils;

import java.util.List;


public class SelPicAdapter extends BaseAdapter {

    private Context context;
    private List<String> list;
    private ISelPic iSelPic;

    public SelPicAdapter(Context context, List<String> list, ISelPic iSelPic) {
        this.context = context;
        this.list = list;
        this.iSelPic = iSelPic;
    }


    @Override
    public int getCount() {
        return list.size() + 1;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public void setData(List<String> list) {

        this.list = list;
        notifyDataSetChanged();
    }


    public List<String> getData() {
        return list;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_sel_pic, parent, false);
            holder = new ViewHolder();
            holder.pic = convertView.findViewById(R.id.sel_pic);
            holder.del = convertView.findViewById(R.id.del_pic);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (position == 0) {
            holder.pic.setImageResource(R.drawable.add_pic);
            holder.del.setVisibility(View.INVISIBLE);
        } else {
            Tools.loadImage(context, list.get(position - 1), holder.pic);
            holder.del.setVisibility(View.VISIBLE);
        }

        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list.size() >= 9) {
                    TsUtils.showToast(context, "不能在添加了");
                    return;
                }
                if (position == 0) {
                    iSelPic.back();
                } else {
                    Tools.enlargePhoto(context, list.get(position - 1), holder.pic);
                }
            }
        });

        holder.del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (position != 0) {
                    list.remove(position - 1);
                    notifyDataSetChanged();
                }
            }
        });

        return convertView;
    }

    private class ViewHolder {
        ImageView pic;
        ImageView del;

    }

    public interface ISelPic {
        void back();
    }

}